/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.util.lang;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 反射工具类
 *
 * @author zeng
 */
public class ReflectUtils {

  /**
   * 对象获取指定属性的值
   *
   * @param obj 要查找的对象
   * @param field 字段名
   */
  public static Object getObjValueToStr(Object obj, Field field) {
    if (obj == null) {
      //
      return null;
    }
    try {
      Method getMethod = new PropertyDescriptor(field.getName(), obj.getClass()).getReadMethod();
      if (getMethod == null) {
        return null;
      }
      return getMethod.invoke(obj);
    } catch (Exception e) {
      try {
        field.setAccessible(true);
        return field.get(obj);
      } catch (Exception ex) {
        ex.addSuppressed(e);
        throw new RuntimeException(ex);
      }
    }
  }

  /**
   * 获取bean中第1个有指定注解的属性名
   *
   * @param obj 要查找的bean
   * @param annoType 注解类型
   * @return 属性名
   */
  public static Field getClassFirstAnnotationFieldName(
      Object obj, Class<? extends Annotation> annoType) {
    return getClassFirstAnnotationField(obj.getClass(), annoType);
  }

  /**
   * 在实体类上获取第一个指定注解的属性
   *
   * @param clazz 要查找的实体类
   * @param annoType 注解类型
   * @return 返回属性
   */
  public static Field getClassFirstAnnotationField(
      Class<?> clazz, Class<? extends Annotation> annoType) {
    if (clazz == null || annoType == null) {
      return null;
    }
    for (Field field : getClassFieldList(clazz)) {
      if (!field.isAnnotationPresent(annoType)) {
        continue;
      }
      return field;
    }
    return null;
  }

  /** 获取类的所有属性 */
  public static List<Field> getClassFieldList(Class<?> clazz) {
    List<Field> list = new ArrayList<>();
    Field[] fields;
    do {
      fields = clazz.getDeclaredFields();
      Collections.addAll(list, fields);
      clazz = clazz.getSuperclass();
    } while (clazz != Object.class && clazz != null);
    return list;
  }
}
